import fs from "node:fs";
import Path from "node:path";
/**
 * @param {string} path  要读取的文件路径。
 * @param {number} start 读取的起始位置。
 * @param {number} end 读取的结束位置。（包含截止位置）
 * @param {string} type 读取的类型。
 * @return {*} 返回一个Promise，该Promise在读取流结束时解析为包含读取数据的Buffer。
 */
export async function createReadStream(
    path: string,
    start: number,
    end: number,
) {
    return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(path, { start, end });
        let chunks: Buffer[] = [];
        readStream.on("data", (chunk: Buffer) => {
            chunks.push(chunk);
        });
        readStream.on("end", () => {
            const buffer = Buffer.concat(chunks);
            resolve(buffer);
        });
    });
}

/**
 *
 *
 * @export
 * @param {string} path 要读取的文件路径。
 * @return {*} 返回文件信息
 */
export async function stat(path: string) {
    return new Promise(async (resolve, reject) => {
        const fileType = await import("file-type");
        const type = await fileType.fileTypeFromFile(path);

        fs.stat(path, (err, stats) => {
            if (err) {
                return reject(err);
            }
            const name = Path.basename(path);
            resolve({
                lastModified: Math.floor(stats.mtimeMs),
                path,
                size: stats.size,
                type: type.mime,
                name,
            });
        });
    });
}
